import { useEffect, useMemo, useState, useRef } from 'react';
import {
    getSuitableZoomNumber,
    getAreaBoundaries,
    generateMask,
    generatePolyline,
    setMarkers,
    showMarkerInfo
} from '@/utils/map.utils'
import { useRecoilValue } from 'recoil';
import { homeState } from '@/store'
import { KUN_SHAN_CENTER } from '@/constants/map.constants'
import { useHomeContext } from '@/pages/home/useHomeContext'
import customMapConfig from '@/data/custom_map_config.json'

import styles from './styles.module.css';

const CustomMap = () => {
    const [mapInstance, setMapInstance ] = useState<BMapGL.Map | null>(null);
    const { elevators } = useRecoilValue(homeState);
    const { homeContext } = useHomeContext();
    const mapRef = useRef(null);

    const alerts: Alert[] = useMemo(() => {
        return elevators.map(((item: Record<string, string | number | keyof MarkerIconMap>) => ({
            point: [item.lng as number, item.lat as number],
            info: item,
            // 弄一个warning的假数据
            status: item.id === '01589f278cc340cab7571ef994124849' ? 'warning' : 'running'
        })))
    }, [elevators])

    useEffect(() => {
        if (window.BMAP_INSTANCE || !mapRef.current) return;

        window.BMAP_INSTANCE = new BMapGL.Map(mapRef.current);
        window.BMAP_INSTANCE.centerAndZoom(new BMapGL.Point(...KUN_SHAN_CENTER), getSuitableZoomNumber());
        window.BMAP_INSTANCE.setMapStyleV2({ styleJson: customMapConfig as BMapGL.MapStyleItem[] });

        (async (map: BMapGL.Map) => {
            const boundaryCoordinatePoints = await getAreaBoundaries('昆山市');

            map.addOverlay(generateMask(boundaryCoordinatePoints));
            map.addOverlay(generatePolyline(boundaryCoordinatePoints));
            setMapInstance(window.BMAP_INSTANCE);
        })(window.BMAP_INSTANCE)

        return () => {
            window.BMAP_INSTANCE = null;
        }
    }, [])

    useEffect(() => {
        if (mapInstance && alerts?.length) {
            setMarkers({
                map: mapInstance,
                items: alerts,
                getMarkerPosition: ({ point }) => point,
                getStatus: ({ status }) => status,
                showInfo: showMarkerInfo(mapInstance),
                markerCategories: {
                    running: !!homeContext?.homeData?.markerCategories?.running,
                    warning: !!homeContext?.homeData?.markerCategories?.warning,
                    inMaintenance: !!homeContext?.homeData?.markerCategories?.inMaintenance,
                    rescueSite: !!homeContext?.homeData?.markerCategories?.rescueSite,
                    rescuedToday: !!homeContext?.homeData?.markerCategories?.rescuedToday
                }
            });
        }
    }, [mapInstance, alerts, homeContext?.homeData?.markerCategories])

    return (
        <div className={styles.container} ref={mapRef}></div>
    )
}

export default CustomMap;